package com.huiyin.utils;

import java.io.File;
import java.util.Map;
import java.util.Random;

import org.json.JSONException;
import org.json.JSONObject;

import android.R.integer;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import com.upyun.block.api.listener.CompleteListener;
import com.upyun.block.api.listener.ProgressListener;
import com.upyun.block.api.main.UploaderManager;
import com.upyun.block.api.utils.UpYunUtils;

public class UPYunUploadUtil {

	private static final String TAG = "UPYunUploadUtil";
	
	private static Context mContext;
	
	// 空间名
	private String bucket = "lehumall";
	// 表单密钥
	private String formApiSecret = "BLS6M/ZW+Q/kvgElS61F/wfjexE=";
	// 保存到又拍云的路径
	private String savePath = "/upload/show/";
	
	private UploadListener mUploadListener;

	public UPYunUploadUtil(Context context) {
		mContext = context;
	}
	
	public void uploadFile(String filePath, UploadListener uploadListener) {
		mUploadListener = uploadListener;
		new UploadTask().execute(filePath);
	}

	public class UploadTask extends AsyncTask<String, integer, String> {

		@Override
		protected String doInBackground(String... params) {

			String filePath = params[0];
			
			if(StringUtils.isEmpty(filePath)) {
				return null;
			}
			
//			savePath = savePath + FileUtils.getFileName(filePath);

			String fileName = String.valueOf(System.currentTimeMillis()) + String.valueOf(new Random().nextInt(100)) + "." + FileUtil.getFileExtension(filePath);
			savePath = savePath + fileName;
			
			File localFile = new File(filePath);
			try {
				/*
				 * 设置进度条回掉函数
				 * 
				 * 注意：由于在计算发送的字节数中包含了图片以外的其他信息，最终上传的大小总是大于图片实际大小，
				 * 为了解决这个问题，代码会判断如果实际传送的大小大于图片
				 * ，就将实际传送的大小设置成'fileSize-1000'（最小为0）
				 */
				ProgressListener progressListener = new ProgressListener() {
					@Override
					public void transferred(long transferedBytes, long totalBytes) {
						// do something...
						Log.d(TAG, "trans:" + transferedBytes + "; total:" + totalBytes);
					}
				};

				CompleteListener completeListener = new CompleteListener() {
					@Override
					public void result(boolean isComplete, String result, String error) {
						// do something...
						Log.d(TAG, "isComplete:" + isComplete + ";result:" + result + ";error:" + error);

						JSONObject jsonObject;
						try {
							jsonObject = new JSONObject(result);
							// 又拍云上传成功返回的地址
						    String upYunBackUrl = JSONParseUtils.getString(jsonObject.getJSONObject("args"), "path");
							if(mUploadListener != null) {
								mUploadListener.onSuccess(upYunBackUrl);
							}
						} catch (JSONException e) {
							e.printStackTrace();
						}

					}
				};

				UploaderManager uploaderManager = UploaderManager.getInstance(bucket);
				uploaderManager.setConnectTimeout(60);
				uploaderManager.setResponseTimeout(60);
				Map<String, Object> paramsMap = uploaderManager.fetchFileInfoDictionaryWith(localFile, savePath);
				// 还可以加上其他的额外处理参数...
				paramsMap.put("return_url", "http://httpbin.org/get");
				// signature & policy 建议从服务端获取
				String policyForInitial = UpYunUtils.getPolicy(paramsMap);
				String signatureForInitial = UpYunUtils.getSignature(paramsMap, formApiSecret);
				uploaderManager.upload(policyForInitial, signatureForInitial, localFile, progressListener, completeListener);

			} catch (Exception e) {
				e.printStackTrace();
			}
			return "result";
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			Log.d(TAG, "result = " + result);
			if (result == null) {
				mUploadListener.onFail();
			}
		}
		
		@Override
		protected void onProgressUpdate(integer... values) {
			super.onProgressUpdate(values);
		}
		
	}
	
	public interface UploadListener {
		void onSuccess(String upYunBackUrl);
		void onFail();
	}
}
